﻿#if UNITY_NETWORK || STEAM_NETWORK
using Manox.Libs.Networking;
#if STEAM_NETWORK
using Manox.Libs.Networking.Steam;
#elif UNITY_NETWORK
using Manox.Libs.Networking.Unity;
#endif
using UnityEngine;


namespace Manox.Libs.Networking
{
    /// <summary>
    /// Network manager.
    /// </summary>
    public class NetworkManager : MonoBehaviour
    {
        /// <summary>Singleton.</summary>
        public static NetworkManager Instance { get; private set; }

        /// <summary>Network node.</summary>
        public NetworkNode NetworkNode { get; private set; }
        

        /// <summary>
        /// Awake.
        /// </summary>
        public void Awake()
        {
            NetworkManager.Instance = this;

            this.InitializeNetwork();
        }

        /// <summary>
        /// Initialize network.
        /// </summary>
        private void InitializeNetwork()
        {
            NetworkMessageTranslator.Instance.RegisterType<SendIdentifyMessage>();
            NetworkMessageTranslator.Instance.RegisterType<AccessGrantedMessage>();
        }

        /// <summary>
        /// Create network node.
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        public NetworkNode CreateNetworkNode(bool server)
        {
#if STEAM_NETWORK
            if (server)
                this.NetworkNode = this.gameObject.AddComponent<SteamNetworkHost>();
            else
                this.NetworkNode = this.gameObject.AddComponent<SteamNetworkClient>();
#elif UNITY_NETWORK
            if (server)
                this.NetworkNode = this.gameObject.AddComponent<UnityNetworkHost>();
            else
                this.NetworkNode = this.gameObject.AddComponent<UnityNetworkClient>();
#endif

            return this.NetworkNode;
        }

        /// <summary>
        /// Remove network node.
        /// </summary>
        public void RemoveNetworkNode()
        {
            Object.DestroyImmediate(this.NetworkNode, true);
        }
    }
}
#endif